package com.alogic.auth.filter;

import com.alogic.auth.Session;
import com.alogic.auth.SessionManager;
import com.alogic.auth.SessionManagerFactory;
import com.alogic.auth.SessionWraper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * 将登录会话作为Principal对象传递
 */
public class AsPrincipal implements Filter {
    private final Logger LOG = LoggerFactory.getLogger(AsPrincipal.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Session session = SessionManagerFactory.getDefault().getSession(httpRequest,httpResponse,true);
        final SessionWraper p = new SessionWraper(session);
        HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
            @Override
            public Principal getUserPrincipal() {
                return p;
            }
        };

        chain.doFilter(wrappedRequest, response);
    }

    @Override
    public void destroy() {

    }
}
